package my.algorithm.base;

public class BinarySearch {

    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int i = bSearch(nums, nums.length, 11);
        System.out.println(i);
    }

    public static int bSearch(int[] nums, int n, int target) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + ((high - low) >> 1);
            System.out.println("low = " + low + ", high = " + high + ", mid = " + mid);
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

    private static int recSearch(int[] nums, int low, int high, int target) {
        if (low > high) return -1;

        int mid = low + ((high - low) >> 1);
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            return recSearch(nums, mid + 1, high, target);
        } else {
            return recSearch(nums, low, mid - 1, target);
        }
    }
}
